//
//  OilRecordViewController.swift
//  ShareCar
//
//  Created by 李帅 on 2018/12/7.
//  Copyright © 2018 changqingkeji. All rights reserved.
//

import UIKit

class OilRecordCell: UITableViewCell {
    @IBOutlet var photoImage: UIImageView!
}

class OilRecordViewController: UIViewController {

    var order: Order.Detail?
    
    var photoPath: String?
    
    var image: UIImage?
    
    var location: CLLocation?
    
    var oilStatus: Int = 0
    
    var photoTime: Int = 0
    
    var photoTimeTimer: Timer?
    
    @IBOutlet weak var dayUploadOilLnstructionLabel: UILabel!
    
    @IBOutlet weak var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        dayUploadOilLnstructionLabel.text = slipViewController?.config?.dayUploadOilInstruction
    }
    
    func photo() {
        #if DEBUG
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.allowsEditing = true
            picker.sourceType = .camera
            self.present(picker, animated: true)
        } else {
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
                let picker = UIImagePickerController()
                picker.delegate = self
                picker.allowsEditing = true
                picker.sourceType = .photoLibrary
                self.present(picker, animated: true)
            } else {
                p("读取相册失败")
            }
        }
        #else
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            let picker = UIImagePickerController()
            picker.delegate = self
            picker.allowsEditing = true
            picker.sourceType = .camera
            present(picker, animated: true)
        } else {
            showError("不支持拍照")
        }
        #endif
    }
    
    @IBAction func oilStatusChange(_ sender: OilSlider) {
        oilStatus = Int(sender.value)
    }
    
    @IBAction func submit(_ sender: Any) {
        
        guard let orderId = order?.orderId else {
            showError("订单号错误")
            return
        }
        
        guard let path = photoPath else {
            showError("未拍摄仪表盘照片")
            return
        }
        JZLoading.showLoadingWith(toView: view)
        Order.confirmOil(orderId: orderId,
                         boardImg: path,
                         oilStatus: oilStatus,
                         location: userLocation,
                         success: { [weak self] in
                            JZLoading.hideLoading()
                            self?.performSegue(withIdentifier: "confirmReturnCarSegue", sender: nil)
        }) { [weak self] msg in
            JZLoading.hideLoading()
            self?.showError(msg)
        }
    }
    
    // MARK: - Navigation

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "confirmReturnCarSegue" {
            if let vc = segue.destination as? ConfirmReturnCarViewController {
                vc.order = order
                vc.location = location
                vc.photoTime = photoTime
            }
        }
    }
    
    deinit {
        photoTimeTimer?.invalidate()
        photoTimeTimer = nil
    }
}

extension OilRecordViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let image = info[UIImagePickerControllerEditedImage] as! UIImage
        
        DispatchQueue.global().async { [weak self] in
            guard let self = self else {
                return
            }
            
            let imgData = image.compress(maxSizeKBytes: kMaxSizeKBytes)
            DispatchQueue.main.async {
                let file = HTTPRequest.File(data: imgData, name: "image_path", fileName: "file.jpg", mimeType: "image/jpg")
                
                JZLoading.showLoadingWith(toView: self.view)
                File.upload(file: file, success: { data in
                    JZLoading.hideLoading()
                    self.photoPath = data?.imagePath
                    self.image = image
                    self.photoTime = Int(Date().timeIntervalSince1970)
                    
                    self.tableView.reloadData()
                    
                    self.photoTimeTimer = Timer.scheduledTimer(withTimeInterval: 5 * 60, repeats: false, block: { timer in
                        self.photoPath = nil
                        self.image = nil
                        
                        self.tableView.reloadData()
                    })
                }) { error in
                    JZLoading.hideLoading()
                    self.showError(error)
                }
                self.dismiss(animated: true)
            }
        }
    }
}

extension OilRecordViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: UITableViewCell
        
        switch indexPath.row {
        case 0:
            cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath)
        case 1:
            cell = tableView.dequeueReusableCell(withIdentifier: "cell2", for: indexPath)
            if let cell = cell as? OilRecordCell, let img = image {
                cell.photoImage.image = img
            }
        case 2:
            cell = tableView.dequeueReusableCell(withIdentifier: "cell3", for: indexPath)
        case 3:
            cell = tableView.dequeueReusableCell(withIdentifier: "cell4", for: indexPath)
        default:
            cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath)
        }
        
        return cell
    }
}

extension OilRecordViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if indexPath.row == 1 {
            photo()
        }
    }
}
